package com.yixing.demo.controller;

import com.yixing.demo.constants.Constants;
import com.yixing.demo.model.Result;
import com.yixing.demo.model.User;
import com.yixing.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @RequestMapping("/login")
    public Result<User> login(String username, String password, HttpSession session) {
        if(!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            return new Result<>(-1, "用户名或密码错误", null);
        }
        User userInfo = userService.login(username);
        if(userInfo == null) {
            return new Result<>(-1, "用户名或密码错误", null);
        }else {
            if(bCryptPasswordEncoder.matches(password, userInfo.getPassword())) {
                userInfo.setPassword("");
                session.setAttribute(Constants.USER_SESSION_KEY, userInfo);
                return new Result<>(1, "登录成功", userInfo);
            }else {
                return new Result<>(-1, "用户名或密码错误", null);
            }
        }
    }
}
